package edu.cornell.cubooks.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

import edu.cornell.cubooks.service.NotificationService;

/**
 * Implementation of the {@link NotificationService}.
 * @author CUBooks team
 *
 */
public class NotificationServiceImpl implements NotificationService {
	
	// defining constants here since they will be accessed only locally
	public static final String DEFAULT_URL = "http://localhost:8080/cubooks/";
	public static final String SUBJECT_FORGOTPASSWD = "Reset your CUBooks password";
	public static final String SUBJECT_SELLER_ACCOUNT_APPROVED ="Your request for the seller account has been approved.";
	public static final String RESTART_PASSWORD_LINK = "user/reset-password.html?";
	public static final String LOGIN_LINK = "login.jsp";
	private String baseUrl = DEFAULT_URL;
	
	@Autowired
	private MailSender mailSender;
	@Autowired
	private SimpleMailMessage templateMessage;
	
	public NotificationServiceImpl(String baseUrl) {
		this.baseUrl = baseUrl;
	}
	
	/*
	 * (non-Javadoc)
	 * @see edu.cornell.cubooks.service.NotificationService#sendResetPasswordEmail(java.lang.String, java.lang.String)
	 */
	public void sendResetPasswordEmail(String emailTo, String token) {
		String subject = SUBJECT_FORGOTPASSWD;
		String message = getBaseUrl() + RESTART_PASSWORD_LINK + "email=" + emailTo + "&token=" + token;
		send(emailTo, subject, message);
	}
	
	/*
	 * (non-Javadoc)
	 * @see edu.cornell.cubooks.service.NotificationService#sendSellerAccountApprovedEmail(java.lang.String)
	 */
	public void sendSellerAccountApprovedEmail(String emailTo) {
		String message =  "Your request for the seller account has been approved. Please try to login to CUbooks @ "+ getBaseUrl() + LOGIN_LINK + " and see your additional options for the seller account.";
		String subject = SUBJECT_SELLER_ACCOUNT_APPROVED;
		send(emailTo, subject, message);
	}
	
	/**
	 * Sends actual message.
	 * 
	 * @param email
	 * @param subject
	 * @param message
	 */
	public void send(String email, String subject, String message) {
		SimpleMailMessage msg = new SimpleMailMessage(templateMessage);
		msg.setTo(email);
		msg.setText(message);
		msg.setSubject(subject);
		try {
			this.mailSender.send(msg);
		} catch (MailException e) {
			e.printStackTrace();
		}
	}

	public String getBaseUrl() {
		return baseUrl;
	}

	public void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}

	public MailSender getMailSender() {
		return mailSender;
	}

	public void setMailSender(MailSender mailSender) {
		this.mailSender = mailSender;
	}

	public SimpleMailMessage getTemplateMessage() {
		return templateMessage;
	}

	public void setTemplateMessage(SimpleMailMessage templateMessage) {
		this.templateMessage = templateMessage;
	}
}